package com.bwie.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/10/23 20:02
 */

public class KaptchaUtils {

    private static DefaultKaptcha kaptcha = null;

    private static DefaultKaptcha defaultKaptcha() {
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "160");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "25");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.space", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

    public static void generateCaptcha(HttpServletResponse response, String captchaText) {
        try {
            if(kaptcha == null) {
                kaptcha = defaultKaptcha();
            }

            // 生成验证码图片
            BufferedImage captchaImage = kaptcha.createImage(captchaText);

            // 设置响应头
            response.setHeader("Cache-Control", "no-store, no-cache");
            response.setContentType("image/jpeg");

            // 输出图片
            ImageIO.write(captchaImage, "jpg", response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
